package com.small.nacos.config.server.utils;

import small.common.core.util.StringUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author zhoujin
 * @Date 2022/11/22 19:10
 */
public class RequestUtil {

    private static final String X_REAL_IP = "X-Real-IP";

    private static final String X_FORWARDED_FOR = "X-Forwarded-For";

    private static final String X_FORWARDED_FOR_SPLIT_SYMBOL = ",";

    private static final String USER_NAME = "username";

    /**
     * 获取请求ip地址
     *
     * @param request
     * @return
     */
    public static String getRemoteIp(HttpServletRequest request) {
        //获取被转发的请求地址
        String xForwardedFor = request.getHeader(X_FORWARDED_FOR);
        if (!StringUtil.isBlank(xForwardedFor)) {
            return xForwardedFor.split(X_FORWARDED_FOR_SPLIT_SYMBOL)[0].trim();
        }
        String nginxHeader = request.getHeader(X_REAL_IP);
        return StringUtil.isBlank(nginxHeader) ? request.getRemoteAddr() : nginxHeader;
    }

    public static String getUser(HttpServletRequest request) {
        return request.getHeader(USER_NAME);
    }

}
